<script lang="ts" setup>
import { useSettingStore } from "./stores/settingStore"
import { nextTick, onMounted, onUnmounted, ref, toRaw } from 'vue'
import SimpleList from '@/components/utils/SimpleList.vue'
import ButtonInput from '@/components/utils/ButtonInput.vue'
import { ElMessage } from 'element-plus'
import TableSelectDialog from '@/components/dialog/TableSelectDialog.vue'
import { useConfigTableStore } from '@/stores/config/configTableStore'
import type { ExportSetting } from "./utils/struct"
const electron = require("electron")

let settingStore = useSettingStore()
let selectedSetting = ref<any>(null)
let exportMethods = ['JSON', 'CSV', 'Excel', 'Custom']
let tableDialogVisible = ref(false)
let configTableStore = useConfigTableStore()

// 初始化数据
let initData = function () {
  electron.ipcRenderer.invoke('getData').then((data: any) => {
    console.log('Loaded export setting data:', data);
    settingStore.initData(data.settings);
    configTableStore.initData(data.table);
  });
}
initData()

// 处理设置列表项点击事件
let handleSettingClick = (id: number) => {
  console.log('Setting clicked:', id);
  selectedSetting.value = settingStore.getExportSetting(id)
  console.log('Selected setting:', selectedSetting.value);
}

// 处理添加设置事件
let handleAddSetting = () => {
  settingStore.addExportSetting()
  saveData()
}

// 处理删除设置事件
let handleDeleteSetting = (index: number) => {
  electron.ipcRenderer.invoke('confirmDelete', `确定要删除该导出设置吗？`).then((result: boolean) => {
    if (result) {
      settingStore.deleteExportSetting(index)
      selectedSetting.value = null
      ElMessage.success('删除成功')
    }
  })
}

// 更新导出分组
let updateExportGroup = (value: number) => {
  if (selectedSetting.value) {
    selectedSetting.value.exportGroupId = value
    saveData()
  }
}

// 更新导出方式
let updateExportMethod = (value: string) => {
  if (selectedSetting.value) {
    selectedSetting.value.exportMethod = value
    saveData()
  }
}

// 添加配表设置
let addTableSetting = () => {
  if (!selectedSetting.value) {
    ElMessage.warning('请先选择导出设置')
    return
  }
  tableDialogVisible.value = true
}

// 处理配表选择确认
let handleTableSelectConfirm = (id: number | null) => {
  if (id !== null) {
    settingStore.addTableSetting(selectedSetting.value.id, id)
    saveData()
    tableDialogVisible.value = false
  } else {
    ElMessage.warning('请选择配表')
  }
}

// 处理配表选择取消
let onTableSelectCancel = () => {
  tableDialogVisible.value = false
}

// 保存数据
let saveData = function () {
  electron.ipcRenderer.invoke('saveSettingStore', toRaw(settingStore.$state)).then((result: any) => {
    if (result.success) {
      // ElMessage.success('保存成功')
    }
  }).catch((error: any) => {
    ElMessage.error('保存失败')
    console.log(error)
  })
}

onMounted(() => {
  // 监听数据更新
  electron.ipcRenderer.on('dataUpdated', (event: any, data: any) => {
    if (data.settings) {
      settingStore.initData(data.settings)
    }
  })
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  electron.ipcRenderer.removeAllListeners('dataUpdated')
})
</script>

<template>
  <div class="export-setting-container">
    <div class="header">
      <el-text size="large" type="primary">导出设置</el-text>
    </div>
    <div class="content">
      <div class="list-container">
        <SimpleList :list="settingStore.exportSettings" @click="handleSettingClick" @add="handleAddSetting"
          @delete="handleDeleteSetting" />
      </div>
      <div class="detail-container" v-if="selectedSetting">
        <el-form :model="selectedSetting" label-width="100px">
          <el-form-item label="设置名称：">
            <ButtonInput v-model="selectedSetting.name" @update:modelValue="saveData" />
          </el-form-item>
          <el-form-item label="描述：">
            <ButtonInput v-model="selectedSetting.desc" @update:modelValue="saveData" />
          </el-form-item>
          <el-form-item label="导出分组：">
            <el-select v-model="selectedSetting.exportGroupId" @change="updateExportGroup">
              <el-option v-for="group in settingStore.exportGroups" :key="group.id" :label="group.name"
                :value="group.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="导出方式：">
            <el-select v-model="selectedSetting.exportMethod" @change="updateExportMethod">
              <el-option v-for="method in exportMethods" :key="method" :label="method" :value="method" />
            </el-select>
          </el-form-item>
        </el-form>
        <div class="table-settings">
          <div class="table-header">
            <el-text>配表设置</el-text>
            <el-button type="primary" size="small" @click="addTableSetting">添加配表</el-button>
          </div>

          <!-- 使用封装的配表选择对话框 -->
          <TableSelectDialog v-model="tableDialogVisible" :tables="configTableStore.tables"
            @confirm="handleTableSelectConfirm" @cancel="onTableSelectCancel" />
          <!-- 移除原有的配表选择下拉框 -->
          <div v-if="selectedSetting.tableSettings && selectedSetting.tableSettings.length > 0">
            <el-table :data="selectedSetting.tableSettings">
              <el-table-column prop="tableId" label="配表ID" />
              <el-table-column prop="exportColumnIds" label="导出列ID"
                :formatter="(row: { exportColumnIds: any[] }) => row.exportColumnIds.join(',')" />
              <el-table-column label="操作">
                <template #default="{ row, $index }">
                  <el-button type="danger" size="small"
                    @click="selectedSetting.tableSettings.splice($index, 1); saveData()">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-else class="no-table-settings">
            <el-text>暂无配表设置</el-text>
          </div>
        </div>
      </div>
      <div class="no-selection" v-else>
        <el-text>请选择一个导出设置</el-text>
      </div>
    </div>
  </div>
</template>

<style scoped>
.export-setting-container {
  padding: 20px;
  height: 100vh;
  box-sizing: border-box;
}

.header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.content {
  display: flex;
  gap: 20px;
  height: calc(100% - 60px);
}

.list-container {
  width: 300px;
  display: flex;
  flex-direction: column;
}

.detail-container {
  flex: 1;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 移除原有detail-item样式，使用ElFormItem的样式 */
/* .detail-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
} */

.table-settings {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-selection {
  display: flex;
  align-items: center;
  gap: 10px;
}

.no-selection,
.no-table-settings {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  padding: 20px;
}
</style>